package com.datastructures2.字符串;


import java.util.Arrays;

/**
 * @author MaoLin Wang
 * @date 2020/10/4 11:06 下午
 */
public class 最长公共前缀 {

    public static String test(String[] strs){
        for (String str : strs) {
            if (str==null || "".equals(str)){
                return "";
            }
        }
        Arrays.sort(strs);
        char[] chars1 = strs[0].toCharArray();
        char[] chars2 = strs[strs.length - 1].toCharArray();

        int num=Math.min(chars1.length,chars2.length);

        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < num; i++) {
            if (chars1[i]==chars2[i]){
                sb.append(chars1[i]);
            }else {
                break;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String[] strings=new String[]{"","abc","abcd"};
        System.out.println(test(strings));

        String[] strings1=new String[]{"abc","abcd","abcde"};
        System.out.println(test(strings1));
    }
}
